package com.ky.tms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ky.tms.entity.SysRouter;
import com.ky.tms.entity.TmsUser;
import com.ky.tms.exception.PredictableException;
import com.ky.tms.mapper.SysRouterMapper;
import com.ky.tms.mapper.TmsUserMapper;
import com.ky.tms.service.ITmsUserService;
import com.ky.tms.util.*;
import com.ky.tms.vo.TmsLogin;
import com.ky.tms.vo.TmsMenu;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chengkaimao
 * @since 2020-03-21
 */
@Service
public class TmsUserServiceImpl extends ServiceImpl<TmsUserMapper, TmsUser> implements ITmsUserService {

    @Value("${jwt.secret}")
    private String secret;



    @Value("${redirect-url}")
    private String redirectUrl;

    @Autowired
    private TmsUserMapper tmsUserMapper;

    @Autowired
    private SysRouterMapper sysRouterMapper;

    @Override
    public Map<String, Object> login(TmsLogin tmsLogin) throws Exception{
        Map<String, Object> result = new HashMap<>();
        QueryWrapper<TmsUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", tmsLogin.getUserName());
        wrapper.eq("password", SecretUtil.md5(tmsLogin.getPassword(),1));
        wrapper.eq("is_valid", 1);
        List<TmsUser> tmsUsers = tmsUserMapper.selectList(wrapper);
        if(tmsUsers.size() != 1){
            throw new PredictableException("用户名或密码错误！");
        }

        TmsUser tmsUser1 = tmsUsers.get(0);
        LocalDateTime now = LocalDateTime.now();
        Date exp = DateUtil.localTimeToDate(LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis() + 1000 * 60 * 60 * 2), ZoneId.systemDefault()));
        String storageStatus = "";
        /*if(tmsLogin.getAutoLogin()){
            storageStatus = "local";
            // 记住14天
            exp = DateUtil.localTimeToDate(LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 14), ZoneId.systemDefault()));
        }else{
            storageStatus = "session";
            // 2小时后无任何操作session失效
            exp = DateUtil.localTimeToDate(LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis() + 1000 * 60 * 60 * 2), ZoneId.systemDefault()));
        }*/
        String sign = JwtUtil.sign(
                secret,
                tmsUser1.getUserName(),
                DateUtil.localTimeToDate(now),
                exp,
                DateUtil.localTimeToDate(now),
                SecretUtil.uuid(),
                storageStatus,
                tmsUser1.getJobTitle()
        );
        result.put("token", sign);
        result.put("type", tmsLogin.getType());
        result.put("autoLogin", tmsLogin.getAutoLogin());
        result.put("redirect", redirectUrl);
        return result;
    }

    @Override
    public Map<String, Object> menuList() throws Exception {
        String role = RequestContextHolderUtil.getRole();
        QueryWrapper<SysRouter> sysRouterQueryWrapper = new QueryWrapper<>();
        sysRouterQueryWrapper.eq("role_code", role);
        List<SysRouter> sysRouters = sysRouterMapper.selectList(sysRouterQueryWrapper);
        if(sysRouters.size() != 1){
            throw new PredictableException("角色编码有误！");
        }

        Map<String, Object> map = JsonUtils.jsonToPojo(sysRouters.get(0).getRouter(), Map.class);
        return map;


        /*Map<String, Object> result = new HashMap<>();
        List<TmsMenu> menuList = new ArrayList<TmsMenu>();
        TmsMenu baseInfo = new TmsMenu();
        baseInfo.setIcon("database");
        baseInfo.setName("基础信息");
        baseInfo.setPath("base-info");
        List<TmsMenu> baseInfoChildren = new ArrayList<TmsMenu>();
        TmsMenu user = new TmsMenu();
        user.setIcon("user-add");
        user.setName("用户管理");
        user.setPath("user");
        user.setModels("tmsUser");
        user.setRoute("/base-info/tmsUser");
        TmsMenu customer = new TmsMenu();
        customer.setIcon("usergroup-add");
        customer.setName("客户管理");
        customer.setPath("customer");
        customer.setModels("customer");
        customer.setRoute("/base-info/customer");
        TmsMenu driver = new TmsMenu();
        driver.setIcon("user-add");
        driver.setName("司机管理");
        driver.setPath("driver");
        driver.setModels("driver");
        driver.setRoute("/base-info/driver");

        baseInfoChildren.add(user);
        baseInfoChildren.add(customer);
        baseInfoChildren.add(driver);
        baseInfo.setChildren(baseInfoChildren);
        menuList.add(baseInfo);

        TmsMenu service = new TmsMenu();
        service.setIcon("phone");
        service.setName("客服中心");
        service.setPath("service");
        List<TmsMenu> serviceChild = new ArrayList<TmsMenu>();
        TmsMenu entryOrder = new TmsMenu();
        entryOrder.setIcon("edit");
        entryOrder.setName("建立订单");
        entryOrder.setPath("entry-order");
        entryOrder.setModels("entryOrder");
        entryOrder.setRoute("/service/entryOrder");

        TmsMenu trackOrder = new TmsMenu();
        trackOrder.setIcon("edit");
        trackOrder.setName("追踪订单");
        trackOrder.setPath("track-order");
        trackOrder.setModels("trackOrder");
        trackOrder.setRoute("/service/trackOrder");

        TmsMenu incomeOrder = new TmsMenu();
        incomeOrder.setIcon("edit");
        incomeOrder.setName("实际收入");
        incomeOrder.setPath("income-order");
        incomeOrder.setModels("incomeOrder");
        incomeOrder.setRoute("/service/incomeOrder");

        serviceChild.add(entryOrder);
        serviceChild.add(trackOrder);
        serviceChild.add(incomeOrder);
        service.setChildren(serviceChild);
        menuList.add(service);

        TmsMenu dispatch = new TmsMenu();
        dispatch.setIcon("car");
        dispatch.setName("运调中心");
        dispatch.setPath("dispatch");

        List<TmsMenu> dispatchChild = new ArrayList<TmsMenu>();

        TmsMenu splitOrder = new TmsMenu();
        splitOrder.setIcon("fullscreen");
        splitOrder.setName("拆分订单");
        splitOrder.setPath("split-order");
        splitOrder.setModels("splitOrder");
        splitOrder.setRoute("/dispatch/splitOrder");

        TmsMenu dispatchOrder = new TmsMenu();
        dispatchOrder.setIcon("money-collect");
        dispatchOrder.setName("提交费用");
        dispatchOrder.setPath("dispatch-order");
        dispatchOrder.setModels("dispatchOrder");
        dispatchOrder.setRoute("/dispatch/dispatchOrder");

        dispatchChild.add(splitOrder);
        dispatchChild.add(dispatchOrder);
        dispatch.setChildren(dispatchChild);
        menuList.add(dispatch);

        TmsMenu operate = new TmsMenu();

        operate.setIcon("compass");
        operate.setName("运营中心");
        operate.setPath("operate");

        List<TmsMenu> operateChild = new ArrayList<TmsMenu>();

        TmsMenu auditCost = new TmsMenu();
        auditCost.setIcon("security-scan");
        auditCost.setName("审核费用");
        auditCost.setPath("audit-cost");
        auditCost.setModels("auditCost");
        auditCost.setRoute("/service/auditCost");

        TmsMenu auditPay = new TmsMenu();
        auditPay.setIcon("security-scan");
        auditPay.setName("审核支付");
        auditPay.setPath("audit-pay");
        auditPay.setModels("auditCost");
        auditPay.setRoute("/operate/auditPay");

        TmsMenu auditIncome = new TmsMenu();
        auditIncome.setIcon("security-scan");
        auditIncome.setName("审核收入");
        auditIncome.setPath("audit-order");
        auditIncome.setModels("incomeOrder");
        auditIncome.setRoute("/operate/auditIncome");

        operateChild.add(auditCost);
        operateChild.add(auditPay);
        operateChild.add(auditIncome);
        operate.setChildren(operateChild);
        menuList.add(operate);

        TmsMenu finance = new TmsMenu();
        finance.setIcon("money-collect");
        finance.setName("财务中心");
        finance.setPath("finance");

        List<TmsMenu> financeChild = new ArrayList<TmsMenu>();

        TmsMenu payCost = new TmsMenu();
        payCost.setIcon("security-scan");
        payCost.setName("支付费用");
        payCost.setPath("pay-cost");
        payCost.setModels("auditCost");
        payCost.setRoute("/finance/payCost");

        TmsMenu ticketPay = new TmsMenu();
        ticketPay.setIcon("money-collect");
        ticketPay.setName("开票");
        ticketPay.setPath("ticket-pay");
        ticketPay.setModels("auditOrder");
        ticketPay.setRoute("/finance/ticketPay");

        TmsMenu gathering = new TmsMenu();
        gathering.setIcon("money-collect");
        gathering.setName("收款");
        gathering.setPath("gathering");
        gathering.setModels("finance");
        gathering.setRoute("/finance/gathering");

        TmsMenu expense = new TmsMenu();
        expense.setIcon("money-collect");
        expense.setName("报销申请");
        expense.setPath("expense");
        expense.setModels("expense");
        expense.setRoute("/finance/expense");

        TmsMenu expenseAudit = new TmsMenu();
        expenseAudit.setIcon("money-collect");
        expenseAudit.setName("报销审核");
        expenseAudit.setPath("expenseAudit");
        expenseAudit.setModels("expense");
        expenseAudit.setRoute("/finance/expenseAudit");

        financeChild.add(payCost);
        financeChild.add(ticketPay);
        financeChild.add(gathering);
        financeChild.add(expense);
        financeChild.add(expenseAudit);
        finance.setChildren(financeChild);
        menuList.add(finance);

        TmsMenu report = new TmsMenu();
        report.setIcon("area-chart");
        report.setName("报表中心");
        report.setPath("report");

        List<TmsMenu> reportChild = new ArrayList<TmsMenu>();

        TmsMenu reportOrder = new TmsMenu();
        reportOrder.setIcon("area-chart");
        reportOrder.setName("订单日报");
        reportOrder.setPath("order");
        reportOrder.setModels("orderReport");
        reportOrder.setRoute("/report/OrderReport");

        TmsMenu costOrder = new TmsMenu();
        costOrder.setIcon("area-chart");
        costOrder.setName("费用日报");
        costOrder.setPath("cost");
        costOrder.setModels("costReport");
        costOrder.setRoute("/report/CostReport");

        TmsMenu invoiceOrder = new TmsMenu();
        invoiceOrder.setIcon("area-chart");
        invoiceOrder.setName("财务日报");
        invoiceOrder.setPath("invoice");
        invoiceOrder.setModels("invoiceReport");
        invoiceOrder.setRoute("/report/InvoiceReport");

        TmsMenu incomeBar = new TmsMenu();
        incomeBar.setIcon("area-chart");
        incomeBar.setName("利润柱状图");
        incomeBar.setPath("incomeBar");
        incomeBar.setRoute("/report/incomeBar");

        TmsMenu incomePie = new TmsMenu();
        incomePie.setIcon("area-chart");
        incomePie.setName("利润饼状图");
        incomePie.setPath("incomePie");
        incomePie.setRoute("/report/incomePie");

        reportChild.add(reportOrder);
        reportChild.add(costOrder);
        reportChild.add(invoiceOrder);
        reportChild.add(incomeBar);
        reportChild.add(incomePie);
        report.setChildren(reportChild);
        menuList.add(report);

        TmsMenu test = new TmsMenu();
        test.setIcon("area-chart");
        test.setName("测试");
        test.setPath("test");

        List<TmsMenu> testChild = new ArrayList<TmsMenu>();

        TmsMenu echarts = new TmsMenu();
        echarts.setIcon("area-chart");
        echarts.setName("echarts");
        echarts.setPath("echarts");
        echarts.setRoute("/Test/Echarts");
        testChild.add(echarts);
        test.setChildren(testChild);
        menuList.add(test);

        result.put("menuList", menuList);
        result.put("defaultRedirect", "base-info/customer");
        return result;*/
    }

    @Override
    public IPage<TmsUser> page(String userName, TmsUser tmsUser, Long limit, Long pages) {
        IPage<TmsUser> page = new Page(pages, limit);
        QueryWrapper<TmsUser> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(tmsUser.getUserName())){
            wrapper.like("user_name", tmsUser.getUserName());
        }
        if(StringUtils.isNotEmpty(tmsUser.getCname())){
            wrapper.like("cname", tmsUser.getCname());
        }
        if(StringUtils.isNotEmpty(tmsUser.getIdCard())){
            wrapper.like("id_card", tmsUser.getIdCard());
        }
        // wrapper.eq("is_valid", 1);
        wrapper.orderByDesc("is_valid");
        wrapper.orderByAsc("sort_val");
        page = this.page(page, wrapper);
        return page;
    }

    @Override
    public void add(String userName, TmsUser tmsUser) throws PredictableException{
        QueryWrapper<TmsUser> wrapper = new QueryWrapper<>();
        wrapper.eq("is_valid", 1);
        wrapper.eq("user_name", tmsUser.getUserName());
        Integer integer = tmsUserMapper.selectCount(wrapper);
        if(integer>0){
            throw new PredictableException("用户名重复！");
        }
        tmsUser.setIsLock(0);
        tmsUser.setIsValid(1);
        tmsUser.setPassword(SecretUtil.md5(tmsUser.getIdCard().substring(1,7),2));
        tmsUser.setCreateTime(LocalDateTime.now());
        tmsUser.setCreateUser(userName);
        tmsUserMapper.insert(tmsUser);
    }

    @Override
    public void delete(String userName, List<Long> ids) {
        tmsUserMapper.deleteByIds(userName, LocalDateTime.now(), ids);
    }

    @Override
    public void update(String userName, TmsUser tmsUser) throws PredictableException {
        QueryWrapper<TmsUser> wrapper = new QueryWrapper<>();
        wrapper.eq("is_valid", 1);
        wrapper.eq("user_name", tmsUser.getUserName());
        wrapper.ne("id",tmsUser.getId());
        Integer integer = tmsUserMapper.selectCount(wrapper);
        if(integer>0){
            throw new PredictableException("用户名重复！");
        }
        tmsUser.setUpdateTime(LocalDateTime.now());
        tmsUser.setUpdateUser(userName);
        tmsUserMapper.updateById(tmsUser);
    }

    @Override
    public void updatePassword(TmsUser tmsUser) throws Exception {
        String userName = RequestContextHolderUtil.getUserName();
        QueryWrapper<TmsUser> wrapper = new QueryWrapper<>();
        wrapper.eq("is_valid", 1);
        wrapper.eq("user_name", userName);
        List<TmsUser> tmsUsers = tmsUserMapper.selectList(wrapper);
        if(tmsUsers.size() != 1){
            throw new PredictableException("账号异常！");
        }
        String oldPassword = tmsUser.getUserName();
        if(!tmsUsers.get(0).getPassword().equals(SecretUtil.md5(oldPassword,2))){
            throw new PredictableException("原密码错误！");
        }
        tmsUsers.get(0).setPassword(SecretUtil.md5(tmsUser.getPassword(),2));
        tmsUserMapper.updateById(tmsUsers.get(0));
    }

    @Override
    public List<Map<String, Object>> selectList() {
        return tmsUserMapper.selectOption();
    }

    @Override
    public void resetPassword(TmsUser tmsUser) throws PredictableException {
        TmsUser tmsUserDb = tmsUserMapper.selectById(tmsUser.getId());
        tmsUserDb.setPassword(SecretUtil.md5(tmsUser.getIdCard().substring(1,7),2));
        tmsUserMapper.updateById(tmsUserDb);
    }
}
